package com.qfedu.openplateform.gateway.filter;

import com.qfedu.openplateform.cache.service.CacheService;
import com.qfedu.openplateform.gateway.config.ApplicationContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 幂等 校验该请求是否处理过
 * 利用签名 验证
 *
 *  1.获取签名
 *  2.使用 redis  setnx  如果对应的签名不存在 返回 true  ---->放行
 *                      如果对应的签名存在 返回 false  ---->拦截  拒绝重复请求
 * @author lileijian
 * @create 2021-12-05 0:56
 */
public class IdempotentFilter implements HandlerInterceptor {
    ThreadLocal<Date> dateLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(dateLocal);
        //记录下当前时间
        System.out.println("当前时间：" + new Date());
        String sign = request.getParameter("sign");

        if(!StringUtils.isEmpty(sign)){
            CacheService cacheService = ApplicationContextHolder.getApplicationContext().getBean(CacheService.class);
            boolean sign1 = cacheService.setNx("sign", sign, 1000);
            if(sign1){
                return true;
            }
        }
        return false;
    }

}
